/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package authentication;

import DAO.UserDAO;
import model.User;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServletValidaLogin extends HttpServlet {

    //private static final long serialVersionUID = 7633293501883840536L;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(); //obtem a sessao do usuario, caso exista

        User user = null;
        String login_form = request.getParameter("username"); // Pega o Login vindo do formulario
        String senha_form = request.getParameter("password"); //Pega a senha vinda do formulario

        try {
            UserDAO dao = new UserDAO();
            user = (User) dao.getUser(login_form, senha_form);
        } catch (Exception e) {
        }

        //se nao encontrou usuario no banco, redireciona para a pagina de erro!
        if (user == null) {
            session.invalidate();
            request.getRequestDispatcher("/errologin.jsp").forward(request, response);
        } else {
            //Se o dao retornar um usuario, coloca o mesmo na sessao
            session.setAttribute("user", user);
            response.sendRedirect("/MetricTools/views/home.jsf");
        }

    }
}
